package com.xinqi.modules.discuss.assistant.service.impl;

import com.alibaba.fastjson2.JSON;
import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.base.response.R;
import com.xinqi.common.core.enums.AssistantMessageTypeEnum;
import com.xinqi.common.core.enums.AssistantStateEnum;
import com.xinqi.modules.chat.chat.official.dto.req.ChatAssistantContentCreateDTO;
import com.xinqi.modules.chat.chat.official.json.BaseMessage;
import com.xinqi.modules.chat.chat.official.json.DiscussionMessage;
import com.xinqi.modules.course.clazz.client.ClassStudentClient;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import com.xinqi.modules.discuss.assistant.AssistantListen;
import com.xinqi.modules.discuss.assistant.convert.AssistantConvert;
import com.xinqi.modules.discuss.assistant.service.AssistantDiscussService;
import com.xinqi.modules.discuss.discuss.domain.CourseDiscussEntity;
import com.xinqi.modules.discuss.discuss.service.CourseDiscussService;
import com.xinqi.modules.discuss.notice.domain.CourseNoticeEntity;
import com.xinqi.modules.user.user.client.UserClient;
import com.xinqi.modules.user.user.dto.rsp.UserResultDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class AssistantDiscussServiceImpl implements AssistantDiscussService {

    @Lazy
    private final AssistantListen assistantListen;

    private final AssistantConvert assistantConvert;

    @Lazy
    private final CourseDiscussService courseDiscussService;

    private final UserClient userClient;

    @Lazy
    private final ClassStudentClient classStudentClient;


    /**
     * 讨论发布消息体
     */
    @Override
    public List<ChatAssistantContentCreateDTO> releaseAssistantDiscuss(Long contentId) {
        CourseDiscussEntity entity = courseDiscussService.getById(contentId);
        if (Objects.isNull(entity)) {
            return null;
        }
        List<ClassStudentResultDTO> students = R.as(classStudentClient.allUserListByClassId(entity.getClassId()));
        List<ChatAssistantContentCreateDTO> list = new ArrayList<>();

        ChatAssistantContentCreateDTO initCreate = assistantListen.initChatAssistantContent(AssistantMessageTypeEnum.DISCUSS);

        DiscussionMessage initMessage = initDiscussMessage(entity);

        students.forEach(item -> {
            ChatAssistantContentCreateDTO create = assistantConvert.create(initCreate);
            create.setContentId(entity.getId());
            if (Objects.equals(YesNoNumberEnum.YES.getCode(), entity.getStatus())) {
                if (entity.getEndTime().isBefore(LocalDateTime.now())) {
                    create.setProgressState(AssistantStateEnum.ENDED.getCode());
                } else {
                    create.setProgressState(AssistantStateEnum.PROGRESS.getCode());
                }
            }
            DiscussionMessage message = assistantConvert.create(initMessage);
            message.setClassRole(item.getClassRole());
            message.setParticipateNum(0);
            message.setNotParticipateNum(0);
            create.setMessageContext(JSON.toJSONString(message));
            create.setRecipient(item.getStudentId());
            create.setSubmittedState(AssistantStateEnum.NOT_PARTICIPATED.getCode());
            list.add(create);
        });
        return list;
    }

    /**
     * 根据作业类型获取要发送学生列表
     */
    private List<ClassStudentResultDTO> getClassStudentList(CourseNoticeEntity entity) {

        // 获取发布者 信息
        ClassStudentResultDTO student = R.as(classStudentClient.findByStudentId(entity.getClassId(), entity.getCreateBy()));

        // 获取班级所有成员信息
        List<ClassStudentResultDTO> students = R.as(classStudentClient.allUserListByClassId(entity.getClassId()));
        // 获取老师以及关系用户信息
        if (Objects.equals(YesNoNumberEnum.YES.getCode(), student.getIsTeacher())) {
            return students.stream().filter(item -> (Objects.equals(YesNoNumberEnum.YES.getCode(), item.getIsRelationalStudent())
                || Objects.equals(YesNoNumberEnum.YES.getCode(), item.getIsTeacher()))
                && !Objects.equals(item.getStudentId(), item.getStudentId())).collect(Collectors.toList());
        } else {
            return students.stream().filter(item -> (Objects.equals(YesNoNumberEnum.YES.getCode(), item.getIsRelationalStudent())
                || Objects.equals(YesNoNumberEnum.YES.getCode(), item.getIsTeacher()))
                && !Objects.equals(item.getPatStuRefId(), item.getPatStuRefId())).collect(Collectors.toList());
        }
    }

    /**
        * 新奇助手初始化发布讨论信息
     */
    private DiscussionMessage initDiscussMessage(CourseDiscussEntity entity) {
        // 初始化消息体
        BaseMessage base = assistantListen.initBaseMessage(entity.getClassId());
        DiscussionMessage message = JSON.parseObject(JSON.toJSONString(base), DiscussionMessage.class);
        message.setContentId(entity.getId());
        message.setTitle(entity.getTitle());

        //根据创建者设置发布者
        R<UserResultDTO> userResultDTO = userClient.findById(entity.getCreateBy());
        message.setPublisher(userResultDTO.getData().getNickname());
        message.setPublisherId(userResultDTO.getData().getId());

        //判断讨论详情内容是否为存在，如果不存在则显示[附件]
        if (Objects.nonNull(entity.getContent())) {
            message.setDiscussionContent(entity.getContent());
        } else {
            // 判断文件内容是否为空
            boolean fileFlag = Objects.nonNull(entity.getFileurls()) && !Objects.equals("[]", entity.getFileurls());
            boolean videoFlag = Objects.nonNull(entity.getVideos()) && !Objects.equals("[]", entity.getVideos());
            boolean imageFlag = Objects.nonNull(entity.getImages()) && !Objects.equals("[]", entity.getImages());
            if (fileFlag || videoFlag || imageFlag) {
                message.setDiscussionContent("[附件]");
            }
        }
        message.setEndTime(entity.getEndTime());
        //如果设置讨论必须回复，则设则消息必须回复
        if (entity.getIsReplay() == 1) {
            message.setRemark("必须回复");
        }
        return message;
    }

}
